package main

import (
	"github.com/xgdapg/wtk"
	"html/template"
	"strconv"
)

func SetTemplateFuncs() {
	wtk.AddTemplateFunc("showHTML", tplShowHTML)
	wtk.AddTemplateFunc("isEqual", tplIsEqual)
	wtk.AddTemplateFunc("fmtDate", tplFmtDate)
	wtk.AddTemplateFunc("urlIndex", tplUrlIndex)
	wtk.AddTemplateFunc("urlPost", tplUrlPost)
	wtk.AddTemplateFunc("urlTags", tplUrlTags)
	wtk.AddTemplateFunc("urlTag", tplUrlTag)
	wtk.AddTemplateFunc("getPages", tplGetPages)
	wtk.AddTemplateFunc("getPrevPage", tplGetPrevPage)
	wtk.AddTemplateFunc("getNextPage", tplGetNextPage)
}

func tplShowHTML(s string) template.HTML {
	return template.HTML(s)
}

func tplIsEqual(s1, s2 string) bool {
	return s1 == s2
}

func tplFmtDate(ts int64) string {
	return getFmtDate(ts, "Y-m-d")
}

func tplUrlIndex(page int) string {
	if page <= 1 {
		return cfg.PrefixPath + "/"
	}
	return cfg.PrefixPath + "/" + strconv.Itoa(page)
}

func tplUrlTags() string {
	return cfg.PrefixPath + "/tags"
}

func tplUrlTag(name string, page int) string {
	if page <= 1 {
		return cfg.PrefixPath + "/tag/" + name
	}
	return cfg.PrefixPath + "/tag/" + name + "/" + strconv.Itoa(page)
}

func tplUrlPost(id int) string {
	return cfg.PrefixPath + "/post/" + strconv.Itoa(id)
}

type tplPage struct {
	Page int
	Curr bool
}

func tplGetPages(maxpage, currpage int) []*tplPage {
	result := []*tplPage{}
	start := currpage - 4
	if start < 1 {
		start = 1
	}
	end := start + 8
	if end > maxpage {
		end = maxpage
	}
	if end-start < 8 {
		start = end - 8
	}
	if start < 1 {
		start = 1
	}
	for i := start; i <= end; i++ {
		result = append(result, &tplPage{
			Page: i,
			Curr: i == currpage,
		})
	}
	return result
}

func tplGetPrevPage(maxpage, currpage int) int {
	result := currpage - 1
	if result < 1 {
		result = 0
	}
	return result
}

func tplGetNextPage(maxpage, currpage int) int {
	result := currpage + 1
	if result > maxpage {
		result = 0
	}
	return result
}
